package zwp.exercise.service.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author zwp14
 * @create 2025/11/26 21:33
 * @description 业务倒计时工具包
 */
public class IdleTimeoutUtils {

    /**
     * 业务计时器，一定时间后停止业务
     */
    public static ScheduledExecutorService startBusiness(long idleTimeoutMs, AtomicLong lastActivityTime) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        System.out.println("业务开始，等待用户操作...若无操作片刻后将终止业务；");

        // 启动定时检查任务
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            long idleTime = System.currentTimeMillis() - lastActivityTime.get();
            if (idleTime >= idleTimeoutMs) {
                closeBusiness(idleTime, scheduledExecutorService);
            }
            // 每秒检查一次
        }, 1, 1, TimeUnit.SECONDS);

        return scheduledExecutorService;
    }

    /**
     * 关闭业务
     *
     * @param idleTime 时间
     */
    private static void closeBusiness(long idleTime, ScheduledExecutorService scheduledExecutorService) {
        System.out.println(idleTime / 1000 + "秒无操作，业务自动关闭！");
        scheduledExecutorService.shutdown();
        System.exit(0);
    }
}
